import React from 'react';
import { connect, DispatchProp } from 'dva';
import { Redirect } from 'react-router-dom';
import { UserModelState } from '@/models/user';
import { withRouter, RouteComponentProps } from 'react-router';

type ConnectProps = { user: UserModelState }

type IProps = DispatchProp & ConnectProps & RouteComponentProps;

const whitePaths = ['/user/login'];

class Authorization extends React.PureComponent<IProps> {
  componentDidMount() {
    if (this.isLogin) {
      // this.props.commit('user/userInfo');
    }
  }

  get location() {
    return this.props.location;
  }

  get userInfo() {
    return this.props.user || {};
  }

  get isLogin() {
    return !!this.userInfo.token;
  }

  get inWhitePage() {
    const {
      pathname,
    } = this.location;
    return whitePaths.includes(pathname);
  }

  render() {
    const { children } = this.props;

    if (this.isLogin && this.inWhitePage) {
      return <Redirect to="/home" />;
    }

    if (!this.isLogin && !this.inWhitePage) {
      return <Redirect to="/user/login" />;
    }

    return children;
  }
}

export default withRouter(connect(
  (state: ConnectProps) => {
    return { user: state.user };
  },
)(Authorization));
